<template>
  <frame-view>
    <!-- 状态栏 -->
    <status-bar></status-bar>
    <!-- 标题栏 -->
    <title-bar :titleProp="getPageTitle" :pageTypeProp="2" />
    <!-- 滚动主体 -->
    <scroll-view>
      <second-page-margin :deviceTypePro="this.deviceType">
        <div class="filterPageContainer" :style="getRingStyle">
          <!-- 进度圆环区 -->
          <div class="ringContainer" :style="getRingStyle">
            <div class="canvas">
              <ring-progress-view
                :deviceTypePro="this.deviceType"
                :percentPro="this.filterLeftPer"
                :darkModePro="this.darkMode"
              ></ring-progress-view>
            </div>
            <div class="titleContainer">
              <div class="top">
                <div class="percent">{{ this.filterLeftPer }}</div>
                <div class="unit">%</div>
              </div>
              <div class="bottom">{{ $t("filter.left") }}</div>
            </div>
          </div>
          <!-- 滤芯剩余时间 和 提示卡片 整体覆盖在圆环区之上-->
          <div class="leftTimeContainer">
            <div :style="getTopMarginViewStyle"></div>
            <div class="leftTimeTitleContainer">
              <div class="leftTimeTitle">{{ $t("filter.title") }}</div>
              <!-- <div class="leftTimeSubTitle">
                {{ $t("filter.subtitle", { hour: this.filterLeftTime }) }}
              </div> -->
            </div>
            <div class="infoCard">
              <div class="content">
                {{ $t("filter.info") }}
              </div>
            </div>
          </div>
        </div>
      </second-page-margin>
    </scroll-view>
  </frame-view>
</template>
<script>
import {
  refreshWebView,
  modifyTitleBar,
  setChangeTitleStyle,
  overrideTitleBarRightBtn,
  setgoSettingListener,
  setMessageVisible,
  getStatusBarHeight,
  setStatuBarHeightListener,
  sendProperty,
  setPropertiesListener,
  setNavigationVisible,
  getDevCacheAll,
  setDevCacheAllListener,
  getProperty,
  toast,
  debugLog,
  userLog,
  getDarkMode,
  finishDeviceActivity,
  deleteDevice,
  modifyDeviceName,
  modifyDeviceNameById,
  modifyRoomName,
  getDeviceInfo,
  setDeviceInfoListener,
  getDevInfoAll,
  setDevInfoAllListener,
  setDeleteDeviceCallBack,
  setModifyDeviceNameCallBack,
  setModifyDeviceNameByIdCallBack,
  setModifyRoomCallBack,
  setSendPropertyListener,
  setRequestPropertyListener,
  setOnResumeListener,
  setOnPauseListener,
  createRule,
  setCreateRuleListener,
  deleteRule,
  setDeleteRuleListener,
  getRules,
  setGetRuleListener,
  controlRuleActive,
  setControlRuleActiveListener,
  jumpToSetting,
  setJumpToSettingListener,
  getSwitchProperties,
  setRequestSwitchPropertiesListener,
  getControlProperties,
  setRequestControlPropertiesListener,
  getStatusProperties,
  setRequestStatusPropertiesListener,
  getGearProperties,
  setRequestGearPropertiesListener,
  getWarnEventProperties,
  setRequestWarnEventPropertiesListener,
  getFaultEventProperties,
  setRequestFaultEventPropertiesListener,
  isScreenSpreaded,
  getCurrentTime,
  getAppLanguage,
} from "../assets/js/device.js";
import {
  WIDTH_PHONE,
  PHONE_RATIO,
  WIDTH_SPREADED,
  SPREADED_RATIO,
  WIDTH_PAD_PORTRAIT,
  PAD_PORTRAIT_RATIO,
  WIDTH_PAD_LANDSCAPE,
  PAD_LANDSCAPE_RATIO,
  WIDTH_STANDARD,
  SPREADED_SCREEN_RATIO,
  selectWidth,
  flexibleWidth,
  flexibleHeight,
  screenDpr,
  screenType,
  screenDescription,
  isIOS,
  isSpreadOn,
  screenSize,
  getSecondPageMarginStyle,
  getSecondPageStyle,
  getDialogFlexAlign,
  getDialogStyle,
  getSingleButtonStyle,
  setScreenResizeListener,
  itemWidth,
} from "../assets/js/flexible.js";
import eventBus from "../assets/js/eventbus.js";

import FrameView from "./custom/frame/FrameView.vue";
import ScrollView from "./custom/frame/ScrollView.vue";
import SecondPageMargin from "./custom/frame/second/SecondPageMargin.vue";
import StatusBar from "./custom/frame/StatusBar.vue";
import TitleBar from "./custom/frame/TitleBar.vue";
import CardDivider from "./custom/CardDivider.vue";
import RingProgressView from "./custom/canvas/RingProgressView.vue";

export default {
  components: {
    FrameView,
    ScrollView,
    SecondPageMargin,
    StatusBar,
    TitleBar,
    CardDivider,
    RingProgressView,
  },
  props: {},
  data() {
    return {
      deviceType: 1,
      darkMode: "light",
      filterLeftTime: 0,
      filterLeftPer: 0,
      filterLevel: 101, //滤芯等级：101-（滤芯等级101，对应的滤芯总使用时间为300小时） 102-（滤芯等级102，对应的滤芯总使用时间为200小时）

      filterElementData: null,
    };
  },
  created() {
    //设备属性事件监听器
    setPropertiesListener(this.propertiesListener);

    //app从后台恢复
    setOnResumeListener(this.updateOnResume);
    //app退到后台
    setOnPauseListener(this.updateOnPause);
  },
  mounted() {
    this.darkMode = this.$route.query.darkMode;
    this.deviceType = screenType;
    setScreenResizeListener(this.updateScreenResize);

    this.filterLeftTime = parseInt(this.$route.query.filterLeftTime);
    this.filterLeftPer = parseInt(this.$route.query.filterLeftPer);

    //添加监听器：右滑或点击系统返回键关闭页面
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL);
      window.addEventListener("popstate", this.goBack, false);
    }
  },
  activated() {},
  destroyed() {
    //移除监听器：右滑或点击系统返回键关闭页面
    window.removeEventListener("popstate", this.goBack, false);
  },
  computed: {
    getTopMarginViewStyle() {
      var dHeight;
      let hwRatio = 188.0 / 252.0;
      switch (this.deviceType) {
        case 101: //iPhone
          dHeight = screenSize(252 * hwRatio + 16 + 32);
          break;
        case 102: //iPad
          dHeight = screenSize(
            (Math.min(flexibleHeight / 2, flexibleWidth) * 0.8 - 64) * hwRatio +
              32 +
              32
          );
          break;
        case 1: //android手机
          dHeight = screenSize(252 * hwRatio + 16 + 32);
          break;
        case 2: //android Pad竖屏
          dHeight = screenSize(
            (Math.min(flexibleHeight / 2, flexibleWidth) * 0.8 - 64) * hwRatio +
              32 +
              32
          );
          break;
        case 3: //android Pad横屏
          dHeight = screenSize(252 * hwRatio + 16 + 32);
          break;
        case 4: //android 折叠屏
          dHeight = screenSize(
            (Math.min(flexibleHeight / 2, flexibleWidth) * 0.8 - 48) * hwRatio +
              24 +
              32
          );
          break;
        default:
          dHeight = screenSize(252 * hwRatio + 16 + 32);
      }

      return {
        width: "100%",
        height: dHeight + "px",
      };
    },
    getRingStyle() {
      switch (this.deviceType) {
        case 101: //iPhone
          return { height: screenSize(252 + 16 * 2) + "px" };
        case 102: //iPad
          return {
            height:
              screenSize(Math.min(flexibleHeight / 2, flexibleWidth) * 0.8) +
              "px",
          };
        case 1: //android手机
          return { height: screenSize(252 + 16 * 2) + "px" };
        case 2: //android Pad竖屏
          return {
            height:
              screenSize(Math.min(flexibleHeight / 2, flexibleWidth) * 0.8) +
              "px",
          };
        case 3: //android Pad横屏
          return { height: screenSize(252 + 16 * 2) + "px" };
        case 4: //android 折叠屏
          return {
            height:
              screenSize(Math.min(flexibleHeight / 2, flexibleWidth) * 0.8) +
              "px",
          };
        default:
          return { height: screenSize(252 + 16 * 2) + "px" };
      }
    },
    getPageTitle() {
      return this.$i18n.t("filter.pageTitle");
    },
  },
  methods: {
    //获取设备基本信息(缓存）的回调方法用于刷新UI
    updateDeviceInfo: function (data) {
      console.log("旧接口getDeviceInfo：");
      console.log(data);
      if (data.errcode) {
        console.log("getDeviceInfo 旧接口返回错误: errcode = ", data.errcode);
      } else {
        //设备所有控制属性值
        if (data.services != null) {
          for (var i = 0; i < data.services.length; i++) {
            this.propertiesListener(data.services[i]);
          }
        }
      }
    },
    //获取设备所有控制属性值的回调方法用于刷新UI
    updateDevInfoAll: function (data) {
      console.log("新接口getDevInfoAll：");
      console.log(data);
      if (data.errcode) {
        console.log("getDevInfoAll 新接口返回错误: errcode = ", data.errcode);
      } else {
        if (data.services != null) {
          for (var i = 0; i < data.services.length; i++) {
            this.propertiesListener(data.services[i]);
          }
        }
      }
    },
    //缓存数据回调方法
    updateDevCacheAll: function (data) {
      console.log(getCurrentTime(), " getDevCacheAll 缓存接口返回结果：");
      console.log(data);
      if (data.errcode) {
        console.log(
          "getDevCacheAll 缓存接口返回错误: errcode = ",
          data.errcode
        );
      } else {
        //更新所有属性值
        if (data.services != null) {
          for (var i = 0; i < data.services.length; i++) {
            this.propertiesListener(data.services[i]);
          }
        }
      }
    },

    //app从后台恢复
    updateOnResume: function () {
      console.log("App从后台恢复到前台");
      // this.isOnResumeUpdating = true;

      //设备属性事件监听器
      setPropertiesListener(this.propertiesListener);

      // //设置获取设备信息的监听器(有缓存)
      setDeviceInfoListener(this.updateDeviceInfo);
      // //获取设备基本信息（有缓存）
      getDeviceInfo();

      //设置获取设备全部数据的结果回调（无缓存）
      setDevInfoAllListener(this.updateDevInfoAll);
      getDevInfoAll();

      //加载缓存信息（离线时调用）
      setDevCacheAllListener(this.updateDevCacheAll);
      getDevCacheAll();
    },
    updateOnPause: function () {
      console.log("App退到后台");
    },
    //处理属性上报事件(处理设备上传的属性事件)
    propertiesListener: function (data) {
      //先缓存数据
      if (data.sid === undefined || data.data === undefined) return;
      if (data.sid === "filterElement") {
        this.filterElementData = data;
      }
      //如果UI更新被锁定，就暂时无法更新UI
      // if (this.uiIsLocking) {
      //   return;
      // }
      //更新UI
      this.updateUI(data);
    },

    //更新UI
    updateUI: function (data) {
      if (data.sid === "filterElement") {
        //滤芯耗材服务:剩余百分比
        if (data.data.leftPercentage !== undefined) {
          this.filterLeftPer = data.data.leftPercentage;
        }
        //滤芯耗材服务：滤芯等级
        if (data.data.filterType !== undefined) {
          this.filterLevel = data.data.filterType;
        }
      }
    },

    updateScreenResize(newScreenType) {
      this.deviceType = newScreenType;
    },
    //返回前一个页面
    goBack: function () {
      //replace替换原路由，作用是避免回退死循环
      this.$router.replace({ path: "/" });
      //关闭页面返回上一级页面时，向上一级页面发送消息
      eventBus.$emit("FoamPage_goback", "我是发泡页面的数据");
      // this.$router.go(-1);//添加右滑或点击系统返回键退出页面的监听器后，不能调用原路由返回
    },
  },
};
</script>
<style scoped>
.filterPageContainer {
  width: 100%;
  position: relative;
}
.filterPageContainer .ringContainer {
  z-index: 1;
  width: 100%;
  height: 252px;
  position: absolute;
}
.filterPageContainer .ringContainer .canvas {
  z-index: 1;
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  /* background: #0000ff; */
}
.filterPageContainer .ringContainer .titleContainer {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 2;
  /* background: #ff00ff; */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.filterPageContainer .ringContainer .titleContainer .top {
  display: flex;
  flex-direction: row;
  align-items: baseline;
}
.filterPageContainer .ringContainer .titleContainer .top .percent {
  font-size: 36px;
  color: var(--current-primary-color);
}
.filterPageContainer .ringContainer .titleContainer .top .unit {
  font-size: 16px;
  color: var(--current-second-title-color);
}
.filterPageContainer .ringContainer .titleContainer .bottom {
  margin-top: 2px;
  font-size: 16px;
  color: var(--current-second-title-color);
}

.filterPageContainer .leftTimeContainer {
  width: 100%;
  /* background: rgb(255, 0, 255, 0.4); */
  position: absolute;
  z-index: 2;
  display: flex;
  flex-direction: column;
}

.filterPageContainer .leftTimeContainer .leftTimeTitleContainer {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.filterPageContainer .leftTimeContainer .leftTimeTitleContainer .leftTimeTitle {
  font-size: 18px;
  color: var(--current-primary-color);
}

.filterPageContainer
  .leftTimeContainer
  .leftTimeTitleContainer
  .leftTimeSubTitle {
  margin-top: 8px;
  font-size: 14px;
  color: var(--current-second-title-color);
}

.filterPageContainer .leftTimeContainer .infoCard {
  display: flex;
  width: 100%;
  margin-top: 32px;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  background: var(--current-card-background-color);
  border-radius: 16px;
}
.filterPageContainer .leftTimeContainer .infoCard .content {
  margin: 12px;
  font-size: 14px;
  color: var(--current-primary-color);
}
</style>
